<template>
  <div class="live_streaming">
    <Header />
    <div class="container">
      <div class="left">
        <div class="info">
          <div class="info_left">
            <div class="avatar">
              <img :src="QNURL + liveStreamingRoomInfo.avatar" alt="" />
            </div>
            <div class="content">
              <span>{{ liveStreamingRoomInfo.roomName }}</span>
              <span>{{ liveStreamingRoomInfo.roomIntroduce }}</span>
            </div>
          </div>
          <div class="info_right">
            <span v-if="type == 0">{{ roomUserList?.length }} 人在看</span>
            <span v-if="type == 1">录播</span>
          </div>
        </div>
        <div class="video_box">
          <video v-if="type == 0" controls muted id="videoElement" />
          <video
            v-if="type == 1"
            :src="liveStreamingUrl"
            controls
            muted
            id="videoElement2"
          />

          <div class="btns" v-if="isShowCloseBtn">
            <el-button type="danger" @click="closeLiveStreamingRoomFun"
              >关闭直播间</el-button
            >
          </div>
        </div>
      </div>
      <div class="right">
        <div class="chat_card">
          <div class="title">
            <span @click="viewChat">聊天</span>
            <span @click="viewUserList">观看用户</span>
          </div>
          <div class="content">
            <div class="chat_list" v-if="currentTabIndex == 0">
              <ul class="msg_content" ref="msgContentRef">
                <li
                  v-for="(item, index) in roomMsgList"
                  :key="index"
                  style="color: #fff"
                >
                  <span class="name">{{ item.nickName }}：</span>
                  <span class="value">{{ item.content }}</span>
                </li>
              </ul>
              <div class="op" v-if="type == 0">
                <el-input v-model="msg" placeholder="输入内容" />
                <el-button class="btn" type="primary" @click="sendMsg"
                  >发送</el-button
                >
              </div>
            </div>
            <div class="user_list" v-if="currentTabIndex == 1">
              <template v-for="(item, index) in roomUserList" :key="index">
                <div class="item">
                  <div class="avatar">
                    <img :src="QNURL + item.avatar" alt="" />
                  </div>
                  <div class="name">
                    <span>{{ item.nickName }}</span>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Header from "@/components/header/Header.vue";
import {
  ref,
  reactive,
  onMounted,
  computed,
  onBeforeUnmount,
  nextTick
} from "vue";
import { Client } from "@stomp/stompjs";
import { useUserStoreHook } from "@/store/modules/user";
import { useRoute } from "vue-router";
import {
  getLiveStreamingRoomChat,
  getLiveStreamingRoomOnlineUser,
  closeLiveStreamingRoom,
  getLiveStreamingRoomUser
} from "@/api/liveStreaming";
import Hls from "hls.js";
import { ElMessage } from "element-plus";
import router from "@/router";
import { WSURL, QNURL } from "@/config/urlConfig";
import { VIDEORECORDURL, LIVESTREAMINGVIDEOURL } from "@/config/urlConfig";

const route = useRoute();

const userStore = useUserStoreHook();

const userInfo = computed(() => userStore.userInfo);

const isShowCloseBtn = computed(
  () => userInfo.value.userId === liveStreamingRoomInfo.userId
);

const liveStreamingRoomId = route.query?.id || "";
const type = Number(route.query?.type) || 0;

let currentTabIndex = ref(0);

const msgContentRef = ref();

let liveStreamingUrl = ref("");

let liveStreamingRoomInfo = reactive<any>({});

// ------------------------------- websocke 连接 -------------------------
// const connectUserList = ref([])
const roomMsgList = ref<any>([]);
const roomUserList = ref<any>([]);

let stompClient = new Client({
  brokerURL: WSURL,
  connectHeaders: {
    Authorization: userInfo.value.userId,
    user: JSON.stringify({
      userId: userInfo.value.userId,
      liveStreamingRoomId: liveStreamingRoomId,
      nickName: userInfo.value.nickname,
      userName: userInfo.value.username,
      avatar: userInfo.value.avatar
    })
  },
  onConnect: () => {
    console.log("Connected");
    var destination = "/topic/" + liveStreamingRoomId + "/queue/messages";

    // 订阅消息
    stompClient.subscribe(destination, function (message: any) {
      let msg = JSON.parse(message.body);

      console.log(msg);

      if (msg?.identifying == "close") {
        router.replace("/home");
        return;
      }

      if (msg?.nickName == "系统") {
        getLiveStreamingRoomUserFun();
      }

      roomMsgList.value.push(msg);

      scrollBottom();
    });
    // 在此处添加其他 onConnect 逻辑，例如订阅主题，发送消息等
  },
  onConnectError: (error: any) => {
    console.error("Connect error:", error);
    // 在此处添加其他 onConnectError 逻辑
    ElMessage.error("连接错误!");
  },
  onDisconnect: () => {
    console.log("Disconnected");
    // 在此处添加其他 onDisconnect 逻辑
  }
});

if (type == 0) {
  stompClient.activate(); // 激活 Stomp 客户端
}

let msg = ref("");

function sendMsg() {
  if (!userStore.getToken) {
    ElMessage.error("请先登录!");
    return;
  }

  let message = {
    liveStreamingRoomId: liveStreamingRoomId,
    userId: userInfo.value.userId,
    content: msg.value,
    userName: userInfo.value.username,
    nickName: userInfo.value.nickname
  };
  const destination = "/app/user.sendMessage";
  const headers = {};

  stompClient.publish({
    destination,
    headers,
    body: JSON.stringify(message)
  });

  msg.value = "";
}

// 逻辑函数
function viewUserList() {
  currentTabIndex.value = 1;
  getLiveStreamingRoomOnlineUserFun();
}

function viewChat() {
  currentTabIndex.value = 0;
  scrollBottom();
}

function scrollBottom() {
  nextTick(() => {
    msgContentRef.value.scrollTop = msgContentRef.value.scrollHeight;
  });
}

// 直播间请求函数
async function getLiveStreamingRoomUserFun() {
  const res = await getLiveStreamingRoomUser({ id: liveStreamingRoomId });

  liveStreamingRoomInfo = Object.assign(liveStreamingRoomInfo, res.data);

  if (type == 0) {
    liveStreamingUrl.value =
      LIVESTREAMINGVIDEOURL + liveStreamingRoomInfo.roomUrl;
    liveStreamingView();
  } else {
    liveStreamingUrl.value = VIDEORECORDURL + liveStreamingRoomInfo.recordUrl;
  }

  if (liveStreamingRoomInfo?.status == 0) {
    router.replace("/home");
  }
}

async function getLiveStreamingRoomChatFun() {
  const res = await getLiveStreamingRoomChat({ id: liveStreamingRoomId });
  console.log(res);
  roomMsgList.value = res.data;
  scrollBottom();
}

async function getLiveStreamingRoomOnlineUserFun() {
  const res = await getLiveStreamingRoomOnlineUser({ id: liveStreamingRoomId });
  console.log(res);
  roomUserList.value = res.data;
}

async function closeLiveStreamingRoomFun() {
  //
  const res = await closeLiveStreamingRoom({ id: liveStreamingRoomId });

  if (res.code == 200) {
    ElMessage.success("关闭成功");
    return;
  }

  ElMessage.error("关闭失败");
}

// ------------------------- 视频展示 -----------------------
let myHls = ref();
// let liveStreamingUrl = ref(
//   "http://192.168.43.253:8848/video/111111-1699603826.mp4"
// );

function liveStreamingView() {
  const video: HTMLVideoElement = document.getElementById(
    "videoElement"
  ) as HTMLVideoElement;

  if (Hls.isSupported()) {
    const hls = new Hls();
    myHls.value = hls;
    hls.loadSource(liveStreamingUrl.value);
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, function () {
      video?.play();
    });
  } else if (video?.canPlayType("application/vnd.apple.mpegurl")) {
    video.src = liveStreamingUrl.value;
    video.addEventListener("loadedmetadata", function () {
      video?.play();
    });
  }
}

onMounted(() => {
  getLiveStreamingRoomUserFun();
  getLiveStreamingRoomChatFun();
  getLiveStreamingRoomOnlineUserFun();
});

onBeforeUnmount(() => {
  stompClient.deactivate();
  if (myHls.value) {
    myHls.value.destroy();
  }
});
</script>

<style lang="scss" scoped>
.live_streaming {
  width: 100%;
  height: 100vh;
  background-color: #30343d;

  #videoElement,
  #videoElement2 {
    width: 100%;
    height: 100%;
  }

  .header {
    width: 100%;
    height: 60px;
    background-color: skyblue;
  }

  .container {
    width: 1200px;
    display: flex;
    margin: 0 auto;
    margin-top: 20px;
  }
}

.left,
.right {
  height: 82vh;
  background-color: #222736;
  border-radius: 10px;
  overflow: hidden;
}

.left {
  width: 800px;
  margin-right: 20px;

  .info {
    width: 100%;
    height: 100px;
    display: flex;
    align-items: center;
    padding: 10px 20px;

    .info_left {
      flex: 2;
      display: flex;
      align-items: center;
      height: 100%;
      .avatar {
        background-color: antiquewhite;
        width: 70px;
        height: 70px;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 10px;
      }

      .content {
        display: flex;
        height: 100%;
        flex-direction: column;
        justify-content: space-around;
        span {
          color: #fff;
        }
      }
    }

    .info_right {
      flex: 1;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      span {
        color: #fff;
      }
    }
  }

  .video_box {
    width: 100%;
    height: calc(100% - 100px);
    // background-color: #000;
    position: relative;

    &:hover {
      .btns {
        visibility: visible;
      }
    }

    .btns {
      position: absolute;
      right: 0;
      top: 0;
      padding: 15px;
      visibility: hidden;
    }
  }
}

.right {
  width: 320px;

  .chat_card {
    width: 100%;
    height: 100%;

    .title {
      width: 100%;
      height: 40px;
      background-color: #1c202c;
      display: flex;

      span {
        flex: 1;
        cursor: pointer;
        line-height: 40px;
        height: 40px;
        text-align: center;
        border-right: 1px solid #ccc;
        color: #fff;

        &:last-child {
          border: none;
        }
      }
    }

    .content {
      width: 100%;
      height: calc(100% - 40px);
      background-color: #222736;
    }
  }
}

.chat_list {
  width: 100%;
  height: 100%;
  position: relative;

  .op {
    width: 100%;
    height: 60px;
    padding: 10px;
    background-color: #1c202c;
    position: absolute;
    left: 0;
    bottom: 0;
    display: flex;
    align-items: center;

    .btn {
      margin-left: 10px;
      background-color: #222736;
    }
  }

  .msg_content {
    width: 100%;
    height: 100%;
    overflow-y: scroll;
    padding: 10px;
    padding-bottom: 60px;
    margin: 0;

    &::-webkit-scrollbar {
      width: 0;
    }

    li {
      width: 100%;
      margin-bottom: 10px;

      .name {
        // font-size: 18px;
      }

      .value {
        color: #666;
      }
    }
  }
}

.user_list {
  width: 100%;
  height: 100%;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    width: 0;
  }

  .item {
    display: flex;
    // background-color: red;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    border-bottom: 1px solid #ccc;
    cursor: pointer;
    align-items: center;

    .avatar {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      overflow: hidden;
      margin-right: 10px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
